package com.cheryjb.examples.spring.transactions.managers;

import java.sql.ResultSet;
import java.sql.SQLException;

import javax.sql.DataSource;

import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.dao.InvalidDataAccessResourceUsageException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.simple.ParameterizedRowMapper;

import com.cheryjb.examples.spring.transactions.model.Person;

/**
 * JdbcTemplate implementation of PersonManagerDao
 * 
 * @author cheryjb
 * 
 */
public class PersonManagerDaoImpl implements PersonManagerDao {

	private final JdbcTemplate jdbcTemplate;

	public PersonManagerDaoImpl(final DataSource dataSource) {
		jdbcTemplate = new JdbcTemplate(dataSource);
	}

	public void clearAll() {
		jdbcTemplate.update("delete from PERSON");
	}

	public void addPerson(final Person person) {
		jdbcTemplate.update(
				"insert into PERSON(id, operationDone) values(?, ?)",
				person.getId(), person.isOperationDone());
	}

	public Person getPerson(final String id) {
		try {
			return jdbcTemplate.queryForObject(
					"select operationDone from PERSON where id=?",
					new ParameterizedRowMapper<Person>() {
						public Person mapRow(final ResultSet rs,
								final int rowNum) throws SQLException {
							return new Person(id, rs
									.getBoolean("operationDone"));
						}
					}, id);
		} catch (final EmptyResultDataAccessException ex) {
			throw new IllegalArgumentException("There's no person with id: "
					+ id);
		}
	}

	public void doOperation(final Person person)
			throws InvalidDataAccessResourceUsageException {
		// In this implementation, if the person id is "3", an Exception is
		// thrown
		if (person.getId().equals("3")) {
			throw new InvalidDataAccessResourceUsageException(
					"intentionally injected fault");
		}
		jdbcTemplate.update("update PERSON set operationDone=? where id=?",
				true, person.getId());

	}

	public void dropRepository() {
		jdbcTemplate.update("drop table if exists PERSON");

	}

	public void createRepository() {
		jdbcTemplate
				.update("create table PERSON(id varchar(32) primary key, firstname varchar(32), lastname varchar(32), operationDone boolean)");
	}

}
